# -*- coding:utf-8 -*-
from common.cipher import cipherhelper
from common import common_strings, command_ids
from shortcuts import g_logger
def battle_process(socket, address):
    # using a makefile because we want to use readline()
    fileobj = socket.makefile()
    while True:
        line = fileobj.readline()
        if not line:
            print ("client disconnected")
            break
        line = line.strip()
        if line == '':
            continue
        try:
            obj_dec = cipherhelper.decode(line)
        except:
            g_logger.error('error while decoding command [%s]' % line)
            continue
        if not hasattr(obj_dec, common_strings.COMMAND_ID):
            g_logger.error('not contain command_id, wrong command string')
            continue
        command = build_command(obj_dec, socket)
        if not command:
            g_logger.error('invalid command_id, %d' % obj_dec[common_strings.COMMAND_ID])
            continue
        command.execute()

def build_command(obj_dec, sock):
    command_id = obj_dec[common_strings.COMMAND_ID]
    if command_id == command_ids.Login:
        from lobby.commands import login_command
        return login_command(obj_dec, sock)
